package org.marketing.common.mq;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

public class SignUtil {
	private static Logger logger = Logger.getLogger(SignUtil.class);
	// 签名生成代码
	public static Map<String, Object> generateSign(Map<String, Object> parm){
    	String _sign = "";
    	if(null != parm){
    		Collection<String> keyset= parm.keySet();  
    		List<String> list = new ArrayList<>(keyset);
    		Collections.sort(list);  
    		for (int i = 0; i < list.size(); i++) {  
    		    _sign+=list.get(i)+"="+parm.get(list.get(i));
    		}  
    		String secretKey = PropertiesUtil.getIdealerInstance().readValue("secret_key");
    		_sign = bytesToMD5((bytesToMD5(_sign.getBytes())+secretKey).getBytes());
    		parm.put("sign", _sign);
    	}
    	
    	return parm;
    }

	// 把字节数组转换成md5
	public static String bytesToMD5(byte[] input) {
		String md5str = null;
		try {
			// 创建一个提供信息摘要算法的对象，初始化为md5算法对象
			MessageDigest md = MessageDigest.getInstance("MD5");
			// 计算后获得字节数组
			byte[] buff = md.digest(input);
			// 把数组每一字节换成16进制连成md5字符串
			md5str = bytesToHex(buff);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return md5str;
	}
	
	public static String bytesToHex(byte[] bytes) {
		StringBuffer md5str = new StringBuffer();
		//把数组每一字节换成16进制连成md5字符串
		int digital;
		for (int i = 0; i < bytes.length; i++) {
			 digital = bytes[i];
			if(digital < 0) {
				digital += 256;
			}
			if(digital < 16){
				md5str.append("0");
			}
			md5str.append(Integer.toHexString(digital));
		}
		return md5str.toString();
	}

}
